package com.dxy.netty.jsonserialize;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * @Description JSON序列化 netty客户端处理器
 * @Author dangxianyue
 * @Date 2023/1/8 15:35
 */
public class JsonSerializeNettyClientHandler extends ChannelInboundHandlerAdapter {
    // 当通道就绪就会触发该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 1; i <= 100; i++) {
            // 发送一个 RpcRequest 对象到服务器
            RpcRequest rpcRequest = new RpcRequest()
                    .setRequestId(i + "")
                    .setClassName("aaa")
                    .setMethodName("bbb")
                    .setParameterTypes(new Class[]{Serializer.class})
                    .setParameters(new Object[]{1});
            ctx.writeAndFlush(rpcRequest);
        }
    }

    // 当通道有读取事件时，会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("收到服务端数据：" + msg);
    }

    // 捕获异常
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
